package net.sea.study.password;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 规则验证链
 */
@Slf4j
public class RuleChain extends AbstractRule {
    private List<IRule> rules = new ArrayList<>();

    /**
     * 添加规则
     *
     * @param rule
     * @return
     */
    public RuleChain addRule(IRule rule) {
        rules.add(rule);
        return this;
    }

    @Override
    public boolean validate(String password) {
        if (!isEnable()) {
            log.info("密码规则验证未启用");
            return true;
        }
        if (CollectionUtil.isEmpty(rules)) {
            log.info("没有注册验证规则");
            return true;
        }
        //根据规则优先级进行排序
        rules.sort(Comparator.comparingInt(IRule::getPriority));
        for (IRule rule : rules) {
            boolean result = rule.validate(password);
            if (!result) {
                return false;
            }
        }
        return true;
    }
}
